<template>
  <div class="box">
    <div class="content_top">
      <img
        src="../assets/logo-study.png"
        alt=""
        style="width: 300px; height: 100px"
      />
      <h6>学情后台管理</h6>
    </div>
    <div class="content_host">
      <h6>用户登录</h6>
      <a-form
        :model="ruleForm"
        :rules="rules"
        ref="formRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <a-form-item
          label="用户名"
          name="usermobile"
          label-width="100px"
          style="color: #ffffff; margin: 20px"
        >
          <a-input
            v-model:value="ruleForm.usermobile"
            autocomplete="off"
          ></a-input>
        </a-form-item>
        <a-form-item
          label="密码"
          name="userpwd"
          label-width="100px"
          style="color: #ffffff; margin: 20px"
        >
          <a-input-password
            type="password"
            v-model:value="ruleForm.userpwd"
            autocomplete="off"
          ></a-input-password>
        </a-form-item>
      </a-form>
      <a-button type="primary" @click="submitForm" style="margin: 20px"
        >登录</a-button
      >
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { Form, Input, Button, message } from "ant-design-vue";
import axios from "axios";
import router from "@/router";
import { generateDynamicRoutes } from "@/router";
import { useStore } from "vuex";
import http from "../routerutils/http";
const store = useStore();
// 然后再登录成功中调用generateDynamicRoutes()

const formRef = ref();
const ruleForm = ref({
  usermobile: "",
  userpwd: "",
});

const rules = {
  usermobile: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      min: 2,
      max: 15,
      message: "用户名长度在 2 到 15 个字符",
      trigger: "blur",
    },
  ],
  userpwd: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      min: 6,
      max: 20,
      message: "密码长度在 6 到 20 个字符",
      trigger: "blur",
    },
  ],
};

// 获取当前用户拥有的权限
const getUserPermissions = async () => {
  try {
    const results = await http.get("/api/permissions/get_permissions");
    console.log("获取当前用户拥有的权限成功：", results);
    const userPermission = results.data.results.map((item: any) => {
      return item.permission_code;
    });
    store.commit("SET_PERMISS", userPermission);
  } catch (error) {
    console.log("获取当前用户拥有的权限失败：", error);
  }
};

// 登录按钮
const submitForm = async () => {
  try {
    // 尝试对表单进行验证，如果验证不通过，则不会执行后续代码
    await formRef.value?.validate();

    // 使用 axios 发送 POST 请求到服务器的登录接口
    // 将用户名和密码作为请求体发送
    const response = await axios.post("/api/users/login", {
      username: ruleForm.value.usermobile, // 用户名字段在请求体中
      password: ruleForm.value.userpwd, // 密码字段在请求体中
    });

    // 打印响应对象到控制台
    console.log(response, "token：：", response.data.data.token);

    // 弹出响应消息提示用户
    message.info(response.data.msg);
    // alert(response.data.msg);

    // 从响应数据中提取 token、用户 ID 和用户名
    const token = response.data.data.token;
    const userid = response.data.data.userInfo.id;
    const username = response.data.data.userInfo.username;
    const role_code = response.data.data.userInfo.rolecode;

    // 将 token、用户 ID 和用户名存储到本地存储（localStorage）
    localStorage.setItem("token", token);
    localStorage.setItem("userid", userid);
    localStorage.setItem("username", username);
    localStorage.setItem("role_code", role_code);

    await getUserPermissions();

    let rolecodeArr = [];
    rolecodeArr.push(role_code);
    store.commit("SET_ROLES", rolecodeArr);

    generateDynamicRoutes();
    // 如果 token 存在，则跳转到后台首页
    if (token) {
      // 跳转到目标页面或默认首页
      const redirectUrl = localStorage.getItem("redirectUrl") || "/admin/home";
      localStorage.removeItem("redirectUrl"); // 清除重定向URL
      router.push(redirectUrl);
    }

    // 打印 token 到控制台，用于调试
    console.log(token);
  } catch (error: any) {
    // 如果请求失败或验证失败，则捕获错误并打印到控制台
    console.error("请求失败:", error);
    message.error(error.response.data.msg);
  }
};

// 检查token是否过期
const token_search = async () => {
  let token = localStorage.getItem("token");
  if (token) {
    // router.push('/admin/BackendHome').catch((error) => {
    //   console.log(error);
    // });
    try {
      let token = localStorage.getItem("token");
      const res = await axios.get("/api/users/check", {
        headers: {
          authorization: `Bear ${token}`,
        },
      });
      console.log(res);
      message.success(res.data.message);
    } catch (error: any) {
      console.log("请求失败", error);
      message.warning(error.response.data.message);
    }
  } else {
    router.push("/login");
    message.warning("您当前登录可能已经过期了！");
  }
};

onMounted(() => {
  token_search();
  // checkToken();
});
</script>

<style scoped>
/* ... Your CSS styles remain the same ... */
.box {
  background: url("../assets/login-back.jpg");
  width: 100%;
  height: 100vh;
}
.content_host {
  width: 450px;
  margin: auto;
}
.content_host > button {
  width: 450px;
  background-color: #007dfe;
  color: #ffffff;
  height: 40px;
  border-radius: 10px;
  font-size: 18px;
  margin: 20px 0;
}
.content_host > p {
  display: flex;
  justify-content: space-between;
  margin: 20px 0;
}
.content_host > p > span {
  font-size: 24px;
  color: #ffffff;
  font-family: SourceHanSerifsc Bold;
}
.content_host > p > input {
  background-color: #ffffff;
  width: 338px;
  height: 40px;
  border-radius: 10px;
}
.content_host > h6 {
  font-size: 24px;
  color: #ffffff;
  font-family: SourceHanSerifsc Bold;
  text-align: center;
  margin: 20px 0;
}
.content_top {
  display: flex;
  justify-content: space-between;
}
.content_top > img {
  margin-top: 40px;
  margin-left: 40px;
}
.content_top > h6 {
  margin-top: 40px;
  margin-right: 40px;
  font-family: SourceHanSerifsc Bold;
  font-size: 24px;
  color: #ffffff;
}
</style>